package com.appcan.base;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;



/**
 * 常用方法�?
 */
public class BaseFunction {

	public static final String DATASOURCE_NULL = "平台查询�?��用DataSource为null";
	/**
	 * 获取JNDI上下文，参数userName和password都不为null，才进行身份认证�?
	 * @param jndiUri		JNDI地址(IP:Port)
	 * @param userName		用户�?
	 * @param password		密码
	 * @return	InitialContext对象
	 * @throws NamingException
	 */
	public static InitialContext createInitialContext(String jndiUri, String userName, String password) throws NamingException{
		InitialContext context = null;
		if(userName == null || password == null){
			context = createInitialContext(jndiUri);
		}
		else{
			Hashtable<String, String> props = new Hashtable<String, String>();
			props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.security.jndi.JndiLoginInitialContextFactory");
			props.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
			props.put(Context.PROVIDER_URL, jndiUri);
			props.put(Context.SECURITY_PRINCIPAL, userName);
			props.put(Context.SECURITY_CREDENTIALS, password);
			context = new InitialContext(props);
		}			
		return context;
	}
	/**
	 * 获取JNDI上下文，
	 * 等同于createInitialContext(String jndiUri, String userName, String password)的参数userName和password都为null
	 * @param jndiUri		JNDI地址(IP:Port)
	 * @return InitialContext对象
	 * @throws NamingException
	 */
	public static InitialContext createInitialContext(String jndiUri) throws NamingException{
		Hashtable<String, String> props = new Hashtable<String, String>();
		props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
		props.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
		props.put(Context.PROVIDER_URL, jndiUri);
		InitialContext context = new InitialContext(props);
		return context;
	}
	/**
	 * 获取DataSource
	 * @return	DataSource对象
	 * @throws NamingException
	 * @throws BusinessException
	 */
	public static DataSource getDataSource() throws NamingException, BusinessException{
		InitialContext ctx = new InitialContext();
		DataSource ds = (DataSource)ctx.lookup(InitListener.getDataSourceJndiName());
		if(ds == null){
			throw new BusinessException(BaseFunction.class, DATASOURCE_NULL);
		}
		return ds;
	}
}
